package com.lingnan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lingnan.dto.NotificationDTO;
import com.lingnan.entity.dto.InterviewReminderDTO;
import com.lingnan.entity.po.Interview;
import com.lingnan.entity.vo.Result;
import com.lingnan.feign.NotificationFeignClient;

import com.lingnan.mapper.InterviewMapper;
import com.lingnan.service.InterviewReminderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class InterviewReminderServiceImpl implements InterviewReminderService {

    private final InterviewMapper interviewMapper;
    private final NotificationFeignClient notificationFeignClient;

    @Override
    public void sendInterviewReminder30Minutes() {
        Date now = new Date();
        Date start = addMinutesToDate(now, 25); // 25-35分钟之间
        Date end = addMinutesToDate(now, 35);

        sendInterviewReminders(start, end, "面试即将开始（30分钟提醒）");
    }

    @Override
    public void sendInterviewReminder1Hour() {
        Date now = new Date();
        Date start = addMinutesToDate(now, 55); // 55-65分钟之间
        Date end = addMinutesToDate(now, 65);

        sendInterviewReminders(start, end, "面试提醒（1小时提醒）");
    }
    private Date addMinutesToDate(Date date, int minutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minutes);
        return calendar.getTime();
    }
    private void sendInterviewReminders(Date start, Date end, String titlePrefix) {
        try {
            List<InterviewMapper.InterviewWithUserInfo> interviews = interviewMapper.getInterviewsForReminder(start, end);

            if (interviews.isEmpty()) {
                log.info("没有需要发送提醒的面试记录");
                return;
            }

            List<NotificationDTO> notifications = new ArrayList<>();

            for (InterviewMapper.InterviewWithUserInfo interview : interviews) {
                // 给HR发送提醒
                NotificationDTO hrNotification = createHRNotification(interview, titlePrefix);
                notifications.add(hrNotification);

                // 给求职者发送提醒
                NotificationDTO seekerNotification = createSeekerNotification(interview, titlePrefix);
                notifications.add(seekerNotification);
            }

            // 使用新的批量发送接口

            sentBatchToAll(notifications);
            log.info("成功发送 {} 条面试提醒通知", notifications.size());

        } catch (Exception e) {
            log.error("发送面试提醒失败", e);
        }
    }

    @Async
    protected Result<Void> sentBatchToAll(List<NotificationDTO> notifications) {
        return notificationFeignClient.batchSendNotificationList(notifications);
    }

    private NotificationDTO createHRNotification(InterviewMapper.InterviewWithUserInfo interview, String titlePrefix) {
    NotificationDTO notification = new NotificationDTO();
    notification.setSenderId(0L); // 系统发送
    notification.setSenderName("系统通知");
    notification.setReceiverId(interview.getHrUserId());
    notification.setReceiverType(0); // 个人通知
    notification.setTitle(titlePrefix + " - " + interview.getJobName());

    // 将Date类型转换为LocalDateTime进行格式化
    LocalDateTime interviewTime = interview.getInterviewTime().toInstant()
        .atZone(java.time.ZoneId.systemDefault())
        .toLocalDateTime();

    notification.setContent(String.format("您有一场面试即将开始：\n\n" +
                    "求职者：%s\n" +
                    "职位：%s\n" +
                    "面试时间：%s\n" +
                    "面试地点：%s\n\n" +
                    "请提前做好准备。",
            interview.getSeekerName(),
            interview.getJobName(),
            interviewTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm")),
            interview.getLocation() != null ? interview.getLocation() : "待确认"));
    notification.setType(1); // 面试提醒类型
    return notification;
}


    private NotificationDTO createSeekerNotification(InterviewMapper.InterviewWithUserInfo interview, String titlePrefix) {
        NotificationDTO notification = new NotificationDTO();
        notification.setSenderId(0L); // 系统发送
        notification.setSenderName("系统通知");
        notification.setReceiverId(interview.getSeekerId());
        notification.setReceiverType(0); // 个人通知
        notification.setTitle(titlePrefix + " - " + interview.getJobName());
        // 将Date类型转换为LocalDateTime进行格式化
        LocalDateTime interviewTime = interview.getInterviewTime().toInstant()
                .atZone(java.time.ZoneId.systemDefault())
                .toLocalDateTime();
        notification.setContent(String.format("您有一场面试即将开始：\n\n" +
                        "面试官：%s\n" +
                        "职位：%s\n" +
                        "面试时间：%s\n" +
                        "面试地点：%s\n\n" +
                        "请提前做好准备，准时参加面试。",
                interview.getHrName(),
                interview.getJobName(),
                interviewTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm")),
                interview.getLocation() != null ? interview.getLocation() : "待确认"));
        notification.setType(1); // 面试提醒类型
        return notification;
    }

@Override
public void sendManualInterviewReminder(Integer interviewId) {
    try {
        // 将LocalDateTime转换为Date类型
        Date startTime = Date.from(LocalDateTime.now().minusHours(1).atZone(ZoneId.systemDefault()).toInstant());
        Date endTime = Date.from(LocalDateTime.now().plusDays(7).atZone(ZoneId.systemDefault()).toInstant());

        List<InterviewMapper.InterviewWithUserInfo> interviews = interviewMapper.getInterviewsForReminder(startTime, endTime);

        InterviewMapper.InterviewWithUserInfo interview = interviews.stream()
                .filter(i -> i.getId()==interviewId)
                .findFirst()
                .orElse(null);

        if (interview == null) {
            log.warn("无法获取面试的用户信息，ID: {}", interviewId);
            return;
        }

        List<NotificationDTO> notifications = new ArrayList<>();
        notifications.add(createHRNotification(interview, "面试提醒"));
        notifications.add(createSeekerNotification(interview, "面试提醒"));

        notificationFeignClient.batchSendNotificationList(notifications);
        log.info("手动发送面试提醒成功，面试ID: {}", interviewId);

    } catch (Exception e) {
        log.error("手动发送面试提醒失败，面试ID: {}", interviewId, e);
    }
}


@Override
public List<InterviewReminderDTO> getUserInterviewReminders(Long userId) {
    // 查询用户未来7天的面试安排
    Date now = new Date();
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(now);
    calendar.add(Calendar.DAY_OF_MONTH, 7);
    Date future = calendar.getTime();

    LambdaQueryWrapper<Interview> wrapper = new LambdaQueryWrapper<>();
    wrapper.between(Interview::getInterviewTime, now, future)
            .eq(Interview::getStatus, 0)
            .orderByAsc(Interview::getInterviewTime);

    List<Interview> interviews = interviewMapper.selectList(wrapper);

    List<InterviewReminderDTO> reminders = new ArrayList<>();
    for (Interview interview : interviews) {
        InterviewReminderDTO reminder = new InterviewReminderDTO();
        reminder.setInterviewId(interview.getId());

        // 将Date格式化为字符串
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        reminder.setInterviewTime(formatter.format(interview.getInterviewTime()));

        reminder.setLocation(interview.getLocation());
        reminder.setSeekerName(interview.getSeekerName());
        reminder.setHrName(interview.getHrName());
        reminder.setJobName(interview.getJobName());
        reminders.add(reminder);
    }

    return reminders;
}

}